#include "InetAddress.h"
#include <strings.h>


InetAddress::InetAddress(const std::string &ip,unsigned short port)
{
    bzero(&_addr,sizeof(_addr));
    _addr.sin_family = AF_INET;
    _addr.sin_port = htons(port);
    //将ip地址转换为网络字节序
    int ret = inet_aton(ip.c_str(),&_addr.sin_addr);
    if (ret==0)
    {
        perror("inet_aton error");
        return;
    }
    
}


InetAddress::InetAddress(const struct sockaddr_in &addr)
: _addr(addr)
{

}

InetAddress::~InetAddress()
{

}
std::string InetAddress::ip()
{
    //将网络字节序转换为点分十进制
    return std::string(inet_ntoa(_addr.sin_addr));
}
unsigned short InetAddress::port()
{
    return ntohs(_addr.sin_port);
}
sockaddr_in *InetAddress::getSockAddrPtr()
{
    return &_addr;
}

std::string InetAddress::to_string()
{
    return "ip="+ip()+",port="+std::to_string(port());
}